<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['promt:channel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['promt:channel:edit']"
        >修改</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="channelList" >
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="金额(元)" align="center" prop="amount" />
      <el-table-column label="免检(元)" align="center" prop="mj" />
      <el-table-column label="上线(元)" align="center" prop="sx" />
      <el-table-column label="有效期(月)" align="center" prop="effectPeriod" />
      <el-table-column label="已领取" align="center" prop="total" />
      <el-table-column label="已使用" align="center" prop="used" />
      <el-table-column label="绑定手机" align="center" prop="relMobile" />
      <el-table-column label="创建时间" align="center" prop="gmtTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state" :formatter="stateFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['promt:channel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-menu"
            class="btn"
            @click="handlePhase(scope.row)"
            v-has-permi="['channel:phase:list']"
          >期号</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改推广渠道对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" maxlength="12"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.state" placeholder="请选择状态">
            <el-option
              v-for="dict in stateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="form.amount"  :min="1" :max="100" label="请输入优惠券金额"></el-input-number> （元）
        </el-form-item>
        <el-form-item label="拆分" prop="amount">
          <el-input-number  size="small" v-model="form.sx"  :min="0" :max="100" label="上线金额"></el-input-number> (上线)
          <el-input-number  size="small"  v-model="form.mj"  :min="0" :max="100" label="免检金额"></el-input-number> (免检)
        </el-form-item>
        <el-form-item label="有效期" prop="effectPeriod">
          <el-input-number v-model="form.effectPeriod"  :min="1" :max="100" label="请输入有效期"></el-input-number> （月）
        </el-form-item>
        <el-form-item label="使用说明" prop="intro">
          <el-input v-model="form.intro" type="textarea" autosize placeholder="请输入内容,多条请使用 竖线分割 |" />
        </el-form-item>
        <el-form-item label="版权信息" prop="copyright">
          <el-input v-model="form.copyright"   placeholder="请输入版权信息" />
        </el-form-item>
        <el-form-item label="绑定手机" prop="relMobile">
          <el-input v-model="form.relMobile"   placeholder="请输入绑定的手机号" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 渠道期号对话框 -->
    <el-dialog title="每期列表" :visible.sync="phaseopen" v-if="phaseopen" width="80%" :append-to-body="true">
      <channel-phase :channelId="channelId"></channel-phase>
    </el-dialog>
  </div>
</template>

<script>
import { listChannel, getChannel, delChannel, addChannel, updateChannel, exportChannel } from "@/api/promt/channel";
import defaultSettings from '@/settings'
import Clipboard from 'clipboard'
import channelPhase from '../phase/index'
export default {
  name: "Channel",
  components:{channelPhase},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 推广渠道表格数据
      channelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      phaseopen: false,
      // 状态  1 启用  2 禁用字典
      stateOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        logo: undefined,
        amount: undefined,
        background: undefined,
        effectPeriod: undefined,
        intro: undefined,
        gmtTime: undefined,
        state: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      promtPre:defaultSettings.promtChannelUrl,
      channelId: undefined
    };
  },
  created() {
    this.getList();
    this.getDicts("promt_channel_state").then(response => {
      this.stateOptions = response.data;
    });
  },
  methods: {
    /** 查询推广渠道列表 */
    getList() {
      this.loading = true;
      listChannel(this.queryParams).then(response => {
        this.channelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态  1 启用  2 禁用字典翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions, row.state);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        logo: undefined,
        amount: 0,
        mj: 0,
        sx: 0,
        background: undefined,
        effectPeriod: undefined,
        intro: undefined,
        gmtTime: undefined,
        state: undefined,
        copyright: undefined,
        relMobile: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加推广渠道";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getChannel(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改推广渠道";
      });
    },
    /** 期号按钮操作 */
    handlePhase(row) {
      this.channelId = row.id;
      this.phaseopen = true;
    },
    handleShare() {
      let clipboard = new Clipboard('.btn')
      clipboard.on('success', e => {
        this.msgSuccess("复制成功");
        clipboard.destroy() // 使用destroy可以清楚缓存
      })
      clipboard.on('error', e => {
        this.msgError("复制失败");
        clipboard.destroy()
      })

    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.mj + this.form.sx != this.form.amount){
            this.msgError("金额拆分总额与优惠券金额不一致，请核对");
            return;
          }
          if (this.form.id != undefined) {
            updateChannel(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addChannel(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除推广渠道编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delChannel(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有推广渠道数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportChannel(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
